const formatTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}
let burl = 'http://47.102.152.116:80'
let bheader = {"content-type": "application/x-www-form-urlencoded" }

const formatDate = (date) => {
  date = new Date(date)
  console.log("date", date)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return (
    [year, month, day].map(formatNumber).join('-')
  )
}

const formatNumber = (n) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

function getAll(){
  return new Promise((resolve, reject)=>{
    wx.request({
      url: burl+'/all',
      header: bheader,
      method: "GET",
      success (res) {
        for (let index = 0; index < res.data.length; index++) {
          res.data[index].due_time = formatDate(new Date(res.data[index].due_time));
        }
        resolve(res.data)
      },
    })
  })
}
//: {'title': '', 'description': '', 'due_time':''}
function postAdd(item){
  console.log("postadd", item)
  return new Promise((resolve, reject)=>{
    wx.request({
      url: burl+'/add',
      header: bheader,
      data: item,
      method: "POST",
      success (res) {
        res.data.due_time = formatDate(new Date(res.data.due_time));
        console.log("addres", res.data)
        resolve(res.data)
      },
    })
  })
}

function postDelete(item){
  return new Promise((resolve, reject)=>{
    wx.request({
      url: burl+'/delete',
      header: bheader,
      data: item,
      method: "POST",
      success (res) {
        resolve(res.data)
      },
    })
  })
}
function postCheck(item){
  return new Promise((resolve, reject)=>{
    wx.request({
      url: burl+'/check',
      header: bheader,
      data: item,
      method: "POST",
      success (res) {
        resolve(res.data)
      },
    })
  })
}

function postUpdate(item){
  console.log("toupdate", item)
  return new Promise((resolve, reject)=>{
    wx.request({
      url: burl+'/update',
      header: bheader,
      data: item,
      method: "POST",
      success (res) {
        console.log("update!", res);
        resolve(res.data)
      },
    })
  })
}

module.exports = {
    formatDate: formatDate,
    postAdd: postAdd,
    getAll: getAll,
    postDelete: postDelete,
    postCheck: postCheck,
    postUpdate: postUpdate
}